package com.kool.kmqtt.server.processer;

import com.kool.kmqtt.server.PacketSender;
import com.kool.kmqtt.server.constant.PacketTypeEnum;
import com.kool.kmqtt.server.encoder.PubrelPacketEncoder;
import com.kool.kmqtt.server.packet.FixedHeader;
import com.kool.kmqtt.server.packet.Packet;
import com.kool.kmqtt.server.packet.PacketIdGenerator;
import com.kool.kmqtt.server.packet.PubrelVariableHeader;
import com.kool.kmqtt.server.parser.PacketParser;
import io.netty.channel.ChannelHandlerContext;

/**
 * PUBREC报文处理器
 */
public class PubrecPacketProcessor extends PacketProcessor {
    public PubrecPacketProcessor(ChannelHandlerContext ctx, PacketParser packetParser) {
        super(ctx, packetParser);
    }

    @Override
    protected void validate(Packet packet) {
        //无校验
    }

    @Override
    protected void processPacket(Packet packet) {
        //取出报文id
        int packetId = packet.getPacketId();
        String clientId = sessionContext.getClientId();
        //删除出站未确认的PULISH消息
        repository.deleteSendPacket(clientId, packetId);

        //构造PUBREL报文
        FixedHeader fixedHeader = new FixedHeader();
        fixedHeader.setPacketType(PacketTypeEnum.PUBREL.getCode());
        fixedHeader.setFlags(2);
        fixedHeader.setRemainingLength(2);

        PubrelVariableHeader pubrelVariableHeader = new PubrelVariableHeader();
        int sendPacketId = PacketIdGenerator.generateId(clientId);
        pubrelVariableHeader.setPacketId(sendPacketId);

        Packet sendPacket = new Packet();
        sendPacket.setPacketId(sendPacketId);
        sendPacket.setFixedHeader(fixedHeader);
        sendPacket.setVariableHeader(pubrelVariableHeader);

        sendPacket.setSendTime(System.currentTimeMillis());
        //保存出站未确认的PUBREL消息
        repository.saveSendPackets(clientId, sendPacket);
        //响应PUBREL报文
        PacketSender packetSender = new PacketSender(sessionContext, new PubrelPacketEncoder());
        packetSender.send(sendPacket);
    }
}
